﻿angular.module('app.dispute', [])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider
        .when('/disputetracking/dispute/:disputeId', {
            templateUrl: 'app/disputetracking/dispute/dispute-list.tpl.html',
            controller: 'disputeCtrl',
            resolve: {
                bdDisputeReasonStatus: ['baseDataProxy', function (baseDataProxy) {
                    return baseDataProxy.SysTypeDetail("025");
                }]
            }
        });
    }])

    .controller('disputeCtrl',
    ['$scope', '$routeParams', 'disputeTrackingProxy', 'commonProxy', 'mailProxy', 'modalService',
        'contactCustomerProxy', 'permissionProxy', 'collectorSoaProxy', 'customerProxy', '$sce',
        function ($scope, $routeParams, disputeTrackingProxy, commonProxy, mailProxy, modalService,
            contactCustomerProxy, permissionProxy, collectorSoaProxy, customerProxy, $sce) {

            $scope.disputeId = $routeParams.disputeId;
            $scope.issReason = "";
            $scope.disputeStatus = "";
            $scope.disputeDate = "";
            $scope.disputeNotes = "";
            $scope.customerNumber = "";
            $scope.disputeStatusCode = "";

            disputeTrackingProxy.queryObject({ id: $scope.disputeId }, function (list) {
                $scope.issReason = list[0];
                $scope.disputeStatus = list[1];
                $scope.disputeDate = list[2];
                $scope.disputeNotes = list[3];
                $scope.customerNumber = list[4];
                $scope.disputeStatusCode = list[5];
                //Get Call List
                commonProxy.query({ customerNum: list[4] }, function (list) {
                    $scope.callhistorylst = list;
                });
                //Get Mail List
                mailProxy.searchMail('&customerNum=' + list[4] + "&customerName=&$filter=(Category ne 'Draft')", '', function (list) {
                    $scope.maillst = list;
                });
                // Get customer name
                customerProxy.getByNum($scope.customerNumber, function (cust) {
                    $scope.customerName = cust.customerName;
                });
            });

            //*****************************************Dispute List***************************s

            $scope.disputeList = {
                data: 'disputelst',
                columnDefs: [
                    {
                        name: 'invoiceNum', displayName: 'Invoice #', enableCellEdit: false, width: '100', pinnedLeft: true,
                        cellTemplate: '<div style="height:30px;vertical-align:middle"><a style="line-height:28px" ng-click="grid.appScope.openInvoiceH(row.entity.invoiceNum)">{{row.entity.invoiceNum}}</a></div>'
                    },
                    { field: 'legalEntity', enableCellEdit: false, displayName: 'Legal Entity', width: '90' },
                    { field: 'invoiceDate', enableCellEdit: false, displayName: 'Invoice Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '100' },

                    { field: 'customerNum', enableCellEdit: false, displayName: 'Customer Code', width: '120' },
                    { field: 'customerName', enableCellEdit: false, displayName: 'Customer Name', width: '120' },


                    { field: 'creditTerm', enableCellEdit: false, displayName: 'Credit Term', width: '100' },
                    { field: 'dueDate', enableCellEdit: false, displayName: 'Due Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '80' },
                    { field: 'purchaseOrder', enableCellEdit: false, displayName: 'Purchase Order', width: '160' },
                    { field: 'saleOrder', enableCellEdit: false, displayName: 'Sale Order', width: '127' },
                    { field: 'rbo', enableCellEdit: false, displayName: 'RBO', width: '120' },
                    { field: 'invoiceCurrency', enableCellEdit: false, displayName: 'Invoice Currency', width: '130' },
                    {
                        field: 'outstandingInvoiceAmount', enableCellEdit: false, displayName: 'Outstanding Invoice Amount', cellFilter: 'number:2', type: 'number', width: '200'
                        , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                            if (parseFloat(grid.getCellValue(row, col)) < 0) {
                                return 'uigridred';
                            }
                        }
                    },
                    {
                        field: 'originalInvoiceAmount', enableCellEdit: false, displayName: 'Original Invoice Amount', cellFilter: 'number:2', type: 'number', width: '180'
                        , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                            if (parseFloat(grid.getCellValue(row, col)) < 0) {
                                return 'uigridred';
                            }
                        }
                    },
                    { field: 'daysLate', enableCellEdit: false, displayName: 'Days Late', width: '80', type: 'number' },
                    { field: 'status', enableCellEdit: false, displayName: 'Status', width: '80' },
                    { field: 'invoiceTrack', enableCellEdit: false, displayName: 'Invoice Track', width: '100' },
                    { field: 'ptpDate', enableCellEdit: false, displayName: 'PTP Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '80' },
                    { field: 'documentType', enableCellEdit: false, displayName: 'Document Type', width: '120' },
                    {
                        field: 'comments', displayName: 'Invoice Memo', width: '120',
                        cellTemplate: '<div><a class="glyphicon glyphicon-pencil" ng-click="grid.appScope.editMemoShow(row.entity.invoiceId,row.entity.invoiceNum,row.entity.comments)"></a>'
                                                    + '<label id="lbl{{row.entity.invoiceId}}" ng-mouseMove="grid.appScope.memoShow(row.entity.invoiceNum,row.entity.comments,$event)" ng-mouseOut="grid.appScope.memoHide()">{{row.entity.comments.substring(0,7)}}...</label></div>'
                    }
                ],

                onRegisterApi: function (gridApi) {
                    //set gridApi on scope
                    $scope.gridApiDisputeList = gridApi;
                }
            };

            $scope.editMemoShow = function (invoiceId, invoiceNum, memo) {
                if (invoiceId != 0) {
                    $scope.selectText = memo;
                    var h = document.documentElement.clientHeight;
                    var w = document.documentElement.clientWidth;
                    var content = document.getElementById('boxEdit');
                    var contentWidth = $('#boxEdit').css('width').replace('px', '');
                    var contentHeight = $('#boxEdit').css('height').replace('px', '');
                    var stop = self.pageYOffset;
                    var sleft = self.pageXOffset;
                    var left = w / 2 - contentWidth / 2 + sleft;
                    var top = h / 2 - contentHeight / 2 + stop;
                    $('#boxEdit').css({ 'left': left + 'px', 'top': top + 'px' });
                    $('#txtBox').css({ 'width': contentWidth - 20 + 'px', 'height': contentHeight - 100 + 'px' });
                    var str = '';
                    var str1 = '';
                    str = 'Invoice :"' + invoiceNum + '" Memo : ';
                    str1 = memo;
                    $("#hiddenInvId").val(invoiceId);
                    $("#lblBoxTitle").html(str);
                    $("#boxEdit").show();
                }
            }

            $scope.batcheditMemoShow = function () {
                $scope.inv = [];
                //for (j = 0; j < $scope.gridApis.length; j++) {
                angular.forEach($scope.gridApiDisputeList.selection.getSelectedRows(), function (rowItem) {
                        if (rowItem.invoiceId != 0) {
                            $scope.inv.push(rowItem.invoiceId);
                        }
                });
                //}
                if ($scope.inv == "" || $scope.inv == null) {
                    alert("Please choose 1 invoice at least .")
                } else {
                    var h = document.documentElement.clientHeight;
                    var w = document.documentElement.clientWidth;
                    var content = document.getElementById('boxEdit');
                    var contentWidth = $('#boxEdit').css('width').replace('px', '');
                    var contentHeight = $('#boxEdit').css('height').replace('px', '');
                    var stop = self.pageYOffset;
                    var sleft = self.pageXOffset;
                    var left = w / 2 - contentWidth / 2 + sleft;
                    var top = h / 2 - contentHeight / 2 + stop;
                    $('#boxEditBatch').css({ 'left': left + 'px', 'top': top + 'px' });
                    $('#batchtxtBox').css({ 'width': contentWidth - 20 + 'px', 'height': contentHeight - 120 + 'px' });
                    var str = '';
                    str = "All Selected Invoices' Memo Will Be Entirely Updated By Follow:"
                    $("#batchhiddenInvId").val($scope.inv);
                    $("#batchtxtBox").val("");
                    $("#batchlblBoxTitle").html(str);
                    $("#boxEditBatch").show();
                }
            }

            $scope.editMemoSave = function () {
                var list = [];
                var invoiceId = $("#hiddenInvId").val();
                var memo = $("#txtBox").val();
                list.push('2');
                list.push(invoiceId);
                list.push(memo);
                collectorSoaProxy.savecommon(list, function () {
                    $scope.saveBack(invoiceId, memo);
                    $scope.editMemoClose();
                });
            }

            $scope.batcheditMemoSave = function () {
                var list = [];
                var invoiceIds = $("#batchhiddenInvId").val().toString();
                var memo = $("#batchtxtBox").val();
                list.push("5");
                list.push(invoiceIds);
                list.push(memo);
                collectorSoaProxy.savecommon(list, function () {
                    $scope.batchsaveBack(memo);
                    $scope.batcheditMemoClose();
                });
            }

            $scope.saveBack = function (invoiceId, memo) {
                angular.forEach($scope.gridApiDisputeList.grid.rows, function (rowItem) {
                    if (rowItem.entity.invoiceId == invoiceId) {
                        rowItem.entity.comments = memo;
                    }
                });
            }

            $scope.batchsaveBack = function (memo) {
                //for (k = 0; k < $scope.gridApis.length; k++) {
                    angular.forEach($scope.gridApiDisputeList.selection.getSelectedRows(), function (rowItem) {
                        if (rowItem.invoiceId != 0) {
                            rowItem.comments = memo;
                        }
                    });
                //}
            }

            $scope.editMemoClose = function () {
                $("#boxEdit").hide();
            }

            $scope.batcheditMemoClose = function () {
                $("#boxEditBatch").hide();
            }

            $scope.memoShow = function (invNum, memo, e) {
                $('#box').css({ 'left': e.pageX - 410 + 'px', 'top': e.pageY + 10 + 'px' });
                var str = '';
                str = 'Invoice :"' + invNum + '" Memo : <br>' + memo;
                $("#box").html(str);
                $("#box").show();

            }

            $scope.memoHide = function () {
                $("#box").hide();
            }

            $scope.openInvoiceH = function (inNum) {
                var modalDefaults = {
                    templateUrl: 'app/soa/invhistory/invhistory.tpl.html',
                    controller: 'invHisCL',
                    size: 'lg',
                    resolve: {
                        inNum: function () { return inNum; }
                    }
                    , windowClass: 'modalDialog'
                };

                modalService.showModal(modalDefaults, {}).then(function (result) {
                });
            }

            //*****************************************Dispute List***************************e
            //Get Dispute List
            disputeTrackingProxy.query({ disId: $scope.disputeId }, function (list) {
                $scope.disputelst = list;
            });

            //*************************************Dispute Status Change List*****************s

            $scope.disputeStatusChangeList = {
                data: 'disStatusChangelst',
                columnDefs: [
                    { field: 'hisDate', displayName: 'Date', cellFilter: 'date:\'yyyy-MM-dd hh:mm:ss\'', width: '140' },
                    { field: 'operator', displayName: 'Collector', width: '490' },
                    { field: 'hisType', displayName: 'Status', width: '465' }
                ],

                onRegisterApi: function (gridApi) {
                    //set gridApi on scope
                    $scope.gridApiStatusChange = gridApi;
                }
            }

            //*************************************Dispute Status Change List*****************e
            //Get Dispute Status Change
            disputeTrackingProxy.query({ disputeid: $scope.disputeId }, function (list) {
                $scope.disStatusChangelst = list;
            });

            //*************************************Call List**********************************s
            $scope.callHistoryList = {
                data: 'callhistorylst',
                columnDefs: [
                    { field: 'contactDate', displayName: 'Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '140' },
                    { field: 'contacterId', displayName: 'Call To', width: '490' },
                    { field: 'comments', displayName: 'Comments', width: '465' }
                ],

                onRegisterApi: function (gridApi) {
                    //set gridApi on scope
                    $scope.gridApiCallHis = gridApi;
                }
            }
            //*************************************Call List**********************************e

            //*************************************Mail List**********************************s
            $scope.mailList = {
                data: 'maillst',
                columnDefs: [
                    { field: 'createTime', displayName: 'Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '140' },
                    { field: 'type', displayName: 'Type', width: '60' },
                    { field: 'from', displayName: 'Mail From', width: '215' },
                    { field: 'to', displayName: 'Mail To', width: '215' },
                    {
                        field: 'tmp', displayName: 'Comments', width: '465',
                        cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()">' +
                                      '<a ng-click=" grid.appScope.getDetail(row.entity)"> {{row.entity.comments}} </a></div>'
                    }
                ],

                onRegisterApi: function (gridApi) {
                    //set gridApi on scope
                    $scope.gridApiMail = gridApi;
                }
            }

            //contactList Detail
            $scope.getDetail = function (row) {
                if (row.messageId) {
                    mailProxy.queryObject({ messageId: row.messageId }, function (mailInstance) {
                        //mailType
                        mailInstance["title"] = "Mail View";
                        mailInstance.viewBody = $sce.trustAsHtml(mailInstance.body);

                        var modalDefaults = {
                            templateUrl: 'app/common/mail/mail-instance.tpl.html',
                            controller: 'mailInstanceCtrl',
                            size: 'customSize',
                            resolve: {
                                custnum: function () { return mailInstance.customerNum; },
                                instance: function () { return mailInstance },
                                mailDefaults: function () {
                                    return {
                                        mailType: 'VI'
                                    };
                                }
                            },
                            windowClass: 'modalDialog'
                        };
                        modalService.showModal(modalDefaults, {}).then(function (result) {

                        });
                    }); //mailProxy
                } else {
                    alert('Mail Id is null')
                }
            }

            //*************************************Mail List**********************************e

            var collectorName = "";
            permissionProxy.getCurrentUser("dummy", function (user) {
                collectorName = user.name;
            }, function (error) {
                alert(error);
            });

            //change table
            $scope.changetab = function (type) {
                if (type == "call") {
                    $scope.inv = [];
                    contactCustomerProxy.queryObject({ contactId: '0' }, function (callInstance) {
                        callInstance["title"] = "Dispute Call";
                        callInstance.logAction = "DISPUTE";
                        var modalDefaults = {
                            templateUrl: 'app/common/contactdetail/contact-call.tpl.html',
                            controller: 'contactCallCtrl',
                            size: 'lg',
                            resolve: {
                                callInstance: function () { return callInstance; },
                                custnum: function () { return $scope.customerNumber; },
                                invoiceIds: function () { return $scope.inv; }
                            },
                            windowClass: 'modalDialog'
                        };
                        modalService.showModal(modalDefaults, {}).then(function (result) {
                            //Get Call List
                            commonProxy.query({ customerNum: $scope.customerNumber }, function (list) {
                                $scope.callhistorylst = list;
                            });
                        });
                    });
                } else if (type == "changestatus") {
                    var modalDefaults = {
                        templateUrl: 'app/common/changestatus/changeStatus-list.tpl.html',
                        controller: 'changeStatusCtrl',
                        resolve: {
                            title: function () { return "Change Dispute Status"; },
                            id: function () { return $scope.disputeId; },
                            type: function () { return "026"; },
                            index: function () { return $scope.disputeStatusCode; },
                            mailId: function () { return ""; }
                        },
                        windowClass: 'modalDialog'
                    };
                    modalService.showModal(modalDefaults, {}).then(function (result) {
                        if (result == "submit") {
                            disputeTrackingProxy.queryObject({ id: $scope.disputeId }, function (list) {
                                $scope.issReason = list[0];
                                $scope.disputeStatus = list[1];
                                $scope.disputeDate = list[2];
                                $scope.disputeNotes = list[3];
                                $scope.customerNumber = list[4];
                                $scope.disputeStatusCode = list[5];
                            });

                            //Get Dispute Status Change
                            disputeTrackingProxy.query({ disputeid: $scope.disputeId }, function (list) {
                                $scope.disStatusChangelst = list;
                            });
                        }
                    });
                } else if (type == "sendmail") {
                    mailProxy.queryObject({ id: 0, type: "NE" }, function (mailInstance) {
                        //SOAFlg
                        mailInstance.soaFlg = "0";
                        //Bussiness_Reference
                        var customerMails = [];
                        angular.forEach($scope.customerNumber.split(','), function (cust) {
                            customerMails.push({ MessageId: mailInstance.messageId, CustomerNum: cust });
                        });
                        mailInstance.CustomerMails = customerMails; //$routeParams.nums;
                        //mailInstance.customerNum = $scope.customerNumber;
                        //subject
                        mailInstance.subject = "Dispute tracking： from(" + collectorName + ")";
                        //title
                        mailInstance["title"] = "Dispute Mail";
                        var modalDefaults = {
                            templateUrl: 'app/common/mail/mail-instance.tpl.html',
                            controller: 'mailInstanceCtrl',
                            size: 'customSize',
                            resolve: {
                                custnum: function () { return $scope.customerNumber; },
                                instance: function () { return mailInstance },
                                mailDefaults: function () {
                                    return {
                                        mailType: 'NE',
                                        mailUrl: disputeTrackingProxy.sendEmailUrl
                                    };
                                }
                            },
                            windowClass: 'modalDialog'
                        };
                        modalService.showModal(modalDefaults, {}).then(function (result) {
                            if (result == "sent") {
                                //Get Mail List
                                //commonProxy.query({ cusNum: $scope.customerNumber }, function (list) {
                                //    $scope.maillst = list;
                                //});

                                mailProxy.searchMail('&customerNum=' + list[4], '', function (list) {
                                    $scope.maillst = list;
                                });
                            }
                        });
                    });
                }
            }

            //Save Special Notes
            $scope.saveNote = function (note) {
                var list = [];
                list.push($scope.disputeId);
                list.push(note);
                disputeTrackingProxy.savenotes(list, function () {
                    alert('success!');
                })
            }

        }])